<!-- 类目管理 -->
<template>
  <div v-loading="loading">
    <el-container v-btn="'product:category:list'">
      <el-tree
        style="width: 100%"
        :data="categoryTree"
        :props="props"
        default-expand-all
        :expand-on-click-node="false"
      >
        <template #default="{ node, data }">
          <div class="custom-tree-node">
            <el-space wrap>
              <el-image
                v-if="data.level == 2"
                style="height: 35px"
                :src="data.picUrl"
              />
              {{ node.label }}
              <el-tag
                v-if="data.level != -1"
                :type="
                  data.level
                    ? 1 == data.level
                      ? 'warning'
                      : 'success'
                    : 'danger'
                "
                >{{
                  data.level ? (1 == data.level ? "二级" : "三级") : "一级"
                }}</el-tag
              >
            </el-space>
            <span>
              <!-- 第三级没有添加，编辑处除了最大的类目都有，删除只有没有子类的有 -->
              <el-button
                type="primary"
                round
                v-if="data.level != 2"
                @click="
                  () => {
                    title = '创建';
                    dialogFrom.parentId = data.id;
                    dialogShow = true;
                  }
                "
                v-btn="'product:category:create'"
                >添加</el-button
              >
              <el-button
                type="warning"
                round
                v-if="data.level != -1"
                @click="editData(data)"
                v-btn="'product:category:edit'"
                >编辑</el-button
              >
              <el-button
                type="danger"
                round
                v-if="!data.childrenList"
                @click="removeCategory(data)"
                v-btn="'product:category:detele'"
                >删除</el-button
              >
            </span>
          </div>
        </template>
      </el-tree>
      <!-- 弹窗 -->
      <el-dialog
        v-model="dialogShow"
        :title="title"
        width="700px"
        destroy-on-close
      >
        <el-form
          ref="formRef"
          :model="dialogFrom"
          :rules="rules"
          :label-width="100"
          @submit.prevent
          status-icon
        >
          <el-form-item label="类目名称" prop="title">
            <el-input v-model.trim="dialogFrom.title" type="text" />
          </el-form-item>
          <el-form-item label="类目图片" prop="picUrl" id="img_box">
            <el-upload
              class="avatar-uploader"
              :show-file-list="false"
              :auto-upload="false"
              @change="progress"
            >
              <img
                v-if="dialogFrom.picUrl"
                :src="dialogFrom.picUrl"
                style="height: 150px"
              />
              <el-icon v-else class="avatar-uploader-icon">
                <Plus />
              </el-icon>
            </el-upload>
          </el-form-item>
        </el-form>
        <template #footer>
          <span>
            <el-button @click="dialogShow = false">取消</el-button>
            <el-button type="primary" @click="debounce(submitForm, 'formRef')"
              >确定</el-button
            >
          </span>
        </template>
      </el-dialog>
    </el-container>
  </div>
</template>

<script>
import Cookie from "js-cookie";
import { post, upload } from "@/utils/http";
import { Plus } from "@element-plus/icons-vue";
export default {
  components: { Plus },
  data() {
    return {
      loading: true, //是否正在加载
      categoryTree: [], //类目树的数据
      dialogShow: false, //是否显示弹窗
      token: "", //管理员请求头,
      title: "", //弹出框的标题
      // 树的属性
      props: {
        children: "childrenList",
        label: "title",
      },
      dialogFrom: { _gp: "admin.category" }, //添加和修改的数据
      // 表单验证的规则
      rules: {
        title: [{ required: true, message: "请输入类目标题" }], // ---类目标题
        picUrl: [{ required: false }], // ---图片
      },
    };
  },
  methods: {
    // 获取类目树的方法
    getTree() {
      this.loading = true;
      post({ _mt: "categoryTree", _gp: "admin.category" }).then((res) => {
        if (200 == res.errno) {
          // console.log(res.data)
          this.categoryTree = [
            {
              childrenList: res.data,
              title: "全部类目",
              level: -1,
              parentId: null,
            },
          ];
          this.loading = false; //加载完毕
        }
      });
    },
    // 删除类目
    removeCategory(data) {
      ElMessageBox.confirm("是否删除该类目?", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          post({
            _gp: "admin.category",
            _mt: "delete",
            id: data.id,
          }).then((res) => {
            if (200 == res.errno) {
              ElMessage.success("删除成功");
              this.getTree();
            }
          });
        })
        .catch(() => {
          ElMessage.info("删除取消");
        });
    },
    // 提交图片的函数
    progress(item) {
      let formData = new FormData();
      let file = item.raw;
      formData.append("file", file);
      upload(formData).then((res) => {
        if (200 == res?.errno) {
          this.dialogFrom.picUrl = res.url; //储存路径到表单
        }
      });
    },
    // 重置表单数据
    resetData() {
      this.dialogFrom = {
        _gp: "admin.category",
        _mt: "",
        title: "", //类目标题
        picUrl: "", //类目图片地址
        parentId: 0, //父类目id
      };
    },
    // 点击编辑时
    editData(row) {
      let { title, picUrl, parentId, id } = row; //获取需要的数据
      Object.assign(this.dialogFrom, { title, picUrl, parentId, id });
      this.title = "编辑";
      this.dialogShow = true;
    },
    // 提交表单数据
    submitForm(formEl) {
      this.$refs[formEl].validate((valid) => {
        if (valid) {
          let data = {};
          Object.assign(data, this.dialogFrom);
          data._mt = this.title == "创建" ? "create" : "update"; //判断是编辑还是添加
          post(data).then((res) => {
            if (200 == res.errno) {
              ElMessage.success(this.title + "成功");
              this.dialogShow = false; //关闭弹窗
              this.getTree(); //刷新数据
            }
          });
        }
      });
    },
  },
  created() {
    this.getTree();
  },
  watch: {
    //弹出框是否显示
    dialogShow(n) {
      if (!n) this.resetData(); //在关闭弹窗时重置数据
      if (this.token) return;
      this.token = { AdminToken: Cookie.get("token") }; //获取token
    },
  },
};
</script>

<style scoped lang="less">
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-left: 10px;
}
.el-tree /deep/.el-tree-node__content {
  height: 50px;
  padding-right: 20px;
  i {
    margin-left: 20px;
  }
}

.el-form {
  display: flex;
  flex-wrap: wrap;
  width: 70%;
  margin-left: 15%;
  .el-form-item {
    width: 100%;
    .el-icon.avatar-uploader-icon {
      border-radius: 6px;
      border: 1px dashed var(--el-border-color);
      font-size: 28px;
      color: #8c939d;
      width: 150px;
      height: 150px;
      text-align: center;
    }
  }
}
</style>
